package com.ztl.mymqtt.mqtt;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import androidx.annotation.Nullable;

public class MyMqttService extends Service implements MqttCallback {

    public final static String Tag = MyMqttService.class.getSimpleName();
    private MqttClient mqttClient;
    private  String brokerUrl = "tcp://10.10.17.127:1885"; // 你可以根据需要更改代理URL
    private  String clientId = MqttClient.generateClientId();
    private  String topic = "testtopic/sub";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        // return null;
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //从共享文件中获取
        MyMqttParas paras=MyMqttParasManager.readConfig(MyMqttService.this);
        brokerUrl=paras.getURI();
        clientId=paras.clientId;
        topic=paras.topicSub;

        connect2Broker();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            mqttClient.disconnect();
        } catch (MqttException e) {
            //throw new RuntimeException(e);
            e.printStackTrace();
        }
    }


   public boolean isConnected=false;
    private void connect2Broker() {
        try {
            mqttClient = new MqttClient(brokerUrl, clientId, new MemoryPersistence());
            mqttClient.setCallback(this);
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);
            options.setConnectionTimeout(5);//设置超时时间，单位：秒
            options.setKeepAliveInterval(20);//心跳包发送间隔，单位：秒

            mqttClient.connect(options);
            mqttClient.subscribe(topic);

            isConnected=true;
        } catch (MqttException e) {
            //throw new RuntimeException(e);
            e.printStackTrace();

            isConnected=false;
        }


    }


    public void subScribe(String topic) {
        if(mqttClient!=null) {
            try {
                mqttClient.subscribe(topic);
            } catch (MqttException e) {
                throw new RuntimeException(e);
            }
        }

    }

    public void unSub(String topic) {
        if (mqttClient != null) {
            try {
                mqttClient.unsubscribe(topic);
            } catch (MqttException e) {
                throw new RuntimeException(e);
            }
        }
    }


    public void publishMessage(String topic, String message) {
        try {
            MqttMessage mqttMessage = new MqttMessage(message.getBytes());
            mqttClient.publish(topic, mqttMessage);
        } catch (MqttException e) {
            //throw new RuntimeException(e);
            e.printStackTrace();
        }
    }


    //region 绑定
    private final IBinder binder = new LocalBinder();

    public class LocalBinder extends Binder {
        public MyMqttService getService() {
            return MyMqttService.this;
        }
    }
    //endregion 绑定


    //region MqttCallback
    @Override
    public void connectionLost(Throwable cause) {
        //连接丢失处理
        Log.d(Tag, "连接丢失处理");
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        //收到消息处理-传递出去
        if (myMqttMsgListener != null) {
            myMqttMsgListener.messageArrived(topic, message);
        }
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        //消息送达处理
        Log.d(Tag, "消息送达处理");
    }
    //endregion MqttCallback


    //region 定义接口用于回调
    public interface MyMqttMsgListener {
        void messageArrived(String topic, MqttMessage message);
    }

    private MyMqttMsgListener myMqttMsgListener;

    public void setMyMqttMsgListener(MyMqttMsgListener listener) {
        this.myMqttMsgListener = listener;
    }
    //endregion 定义接口用于回调


}
